package com.lyw.home

import android.app.Application
import android.content.Context
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.Utils
import com.lyw.db.DatabaseProvider
import com.lyw.db.entites.Question
import com.lyw.home.bean.KnowledgeSubTypeInfo
import com.lyw.home.bean.KnowledgeTypeInfo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.withContext
import java.io.InputStreamReader

object QuestionRepository {


    suspend fun getKnowLedgeType(): List<KnowledgeTypeInfo> {
        val test = mutableListOf(
            KnowledgeTypeInfo(
                "android", 1, true,
                mutableListOf<KnowledgeSubTypeInfo>()
            )
        )
        test.add(KnowledgeTypeInfo("java", 2, false, mutableListOf()))
        test.add(KnowledgeTypeInfo("Kotlin", 3))
        test.add(KnowledgeTypeInfo("flutter", 4))
        test
        return test
    }

    suspend fun getKnowledgeTypeInfo(knowledgeType: Int): List<Question> {
        return DatabaseProvider.getDatabase().questionDao()
            .getQuestionsByKnowledgeType(knowledgeType)
    }

    private fun loadJsonFromAsset(context: Context, filename: String): String {
        val inputStream = context.assets.open(filename)
        val reader = InputStreamReader(inputStream, "UTF-8")
        val bufferedReader = reader.buffered()
        return bufferedReader.use { it.readText() }
    }
    suspend fun loadKnowledgeList(topType: String): List<ContentItem> = loadAssetList(topType,"knowledge")
    suspend fun loadLearnList(topType: String): List<ContentItem> = loadAssetList(topType,"learn")
    suspend fun loadAssetList(topType: String, subType: String): List<ContentItem> =
        withContext(Dispatchers.IO) {
            var learnTypesTemp = mutableListOf<ContentItem>()
            LogUtils.d("topType:${topType}")
            Utils.getApp().assets.list(topType)?.filter {
                it == subType
            }?.forEach { _ ->
                Utils.getApp().assets.list("$topType/$subType")?.forEach { fileName ->
                    runCatching {
                        var name = fileName.substring(0, fileName.indexOf("."))
                        learnTypesTemp.add(ContentItem(name, "$topType/$subType/$fileName",topType, subType,0))
                    }.exceptionOrNull()?.let {
                        LogUtils.d("$fileName error")
                        it.printStackTrace()
                    }
                }
            }
            LogUtils.d("learnTypesTemp:${learnTypesTemp.size}")
            learnTypesTemp
        }


    suspend fun getQuestionsByType(topType: String,subType:String,knowledgeType: Int): List<Question>{
        LogUtils.d("topType:${topType},subType:${subType}")
        return DatabaseProvider.getDatabase().questionDao().getQuestionsByType(topType,subType,knowledgeType)
    }

    private suspend fun initDbByType(topType: String, subType: String, type:Int):Int {
        var localIndex = type
        Utils.getApp().assets.list(topType)?.filter {
            it == subType
        }?.forEach { type ->
            runCatching {
//                LogUtils.d("type:${type}")
                Utils.getApp().assets.list("$topType/$type")?.forEach { fileName ->
//                    LogUtils.d("path:$topType/$type/$fileName")
                    DatabaseProvider.insertQuestionsFromJson(
                        topType,
                        subType,
                        loadJsonFromAsset(
                            Utils.getApp(),
                            "$topType/$type/$fileName"
                        ), localIndex
                    )
                    localIndex++
//                    LogUtils.d("fileName:${fileName}")
                    var name = fileName.substring(0, fileName.indexOf("."))
//                    learnTypesTemp.add(ContentItem(name,"android/$type/$fileName"))
                }

            }.exceptionOrNull()?.let {
//                    LogUtils.d("$fileName error")
                it.printStackTrace()
            }

        }
        return localIndex

    }

    suspend fun initDb() {
        DatabaseProvider.init(Utils.getApp())
        DatabaseProvider.getDatabase().questionDao().deleteAll();
        initDbByType("android", "learn",0)
        initDbByType("java", "learn",0)
       initDbByType("flutter", "learn",0)
    }
}